//
//  WBMainViewController.swift
//  Weibo
//
//  Created by Albert Zhu on 16/9/28.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit

// 主控制器
class WBMainViewController: UITabBarController {
    
    lazy var composeButton: UIButton = UIButton.az_imageButton("tabbar_compose_icon_add", "tabbar_compose_button")
    
    var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildController()
        setupComposeButton()
        setupTimer()
        updateTimer()
        setupNewFeatures()
        
        delegate = self
        
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin(noti:)), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    @objc func userLogin(noti: Notification) {
       debugPrint(noti)
        
        let vc = WBOAuthViewController()
        
        present(UINavigationController.init(rootViewController: vc), animated: true, completion: nil)
    }
    
    deinit {
        timer?.invalidate()
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    // MARK: - 按钮监听方法
    func composeStart() {
        
        // 判断是否登录
        if !WBNetworkManager.shared.userLogon {return}
        
        // 实例化撰写微博视图
        let view = WBComposeTypeView.composeTypeView()
        
        // 显示视图
        weak var weakView = view
        
        // 此处view会引起循环引用，因此需要弱引用
        view.show{ className in
            guard let className = className,
                let cls = NSClassFromString("\(Bundle.main.nameSpace).\(className)") as? UIViewController.Type else {
                    weakView?.removeFromSuperview()
                    return
            }
            
            /// 通过反射获取类名一定要加上命名空间: Bundle.main.nameSpace + . + 类名，否则会崩溃
            let vc =  cls.init()
            let nav = UINavigationController(rootViewController: vc)
            
            // 使导航控制器下的所有子视图强行更新约束
            nav.view.layoutIfNeeded()
            
            self.present(nav, animated: true) {
                
                weakView?.removeFromSuperview()
            }
        }
    }
}


// MARK: - UITabBarControllerDelegate
extension WBMainViewController: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        let idx = childViewControllers.index(of: viewController)
        
        if selectedIndex == 0 && idx == selectedIndex {
            
            debugPrint("点击首页")
            
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.viewControllers[0] as! WBHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -(64 + CZRefreshOffset)), animated: true)
            vc.refreshControl?.beginRefreshing()
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                vc.loadData()
            })
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
}

// MARK: - 定时器
extension WBMainViewController {
    
    func setupTimer() {
        
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    @objc func updateTimer() {
        
        if !WBNetworkManager.shared.userLogon {
            return
        }
        
        WBNetworkManager.shared.unreadCount { (count) in
            self.tabBar.items?.first?.badgeValue = count > 0 ? "\(count)" : nil
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

// 类似OC分类，可以用来切分代码块
// 可以把相近功能的方法放在一个extension中
// 便于维护代码
// 和OC分类一样，extension只能定义方法和计算属性，不可以定义存储属性
// MARK: - 设置界面
private extension WBMainViewController {
    
    // 设置tabbar中间的"添加"按钮
    func setupComposeButton() {
        // 每个item的宽度，减1是为了覆盖住一个点宽度的容错点
        let w = tabBar.bounds.width / CGFloat(childViewControllers.count) - 1
        // 这个方法是通过距离父控件左侧和上侧距离来设置frame
        composeButton.frame = tabBar.bounds.insetBy(dx: w * 2, dy: 0)
        tabBar.addSubview(composeButton)
        
        composeButton.addTarget(self, action: #selector(composeStart), for: .touchUpInside)
    }
    
    func setupChildController() {
        
        // 获取沙盒json路径
        let jsonPath = "main.json".az_appendDocumentDir()
        var data = NSData(contentsOfFile: jsonPath)
        
        if data == nil {
            // 沙盒没有json文件，则加载bundle的json文件
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            
            data = NSData(contentsOfFile: path!)
        }
        
        // 取地址，获取json数据，解析成数据源数组
        guard  let array = try! JSONSerialization.jsonObject(with: data as! Data, options: .mutableContainers) as? [[String:Any]]
            else {return}
        
        var arrayM = [UIViewController]()
        for dict in array {
            
            arrayM.append(controller(dict: dict))
        }
        
        viewControllers = arrayM
    }
    
    /// 使用字典创建一个子控制器
    ///
    /// - parameter dict: 信息字典
    ///
    /// - returns: 子控制器
    private func controller(dict: [String:Any]) -> UIViewController {
        // 取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let visitorInfo = dict["visitorInfo"] as? [String:String],
            let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? WBBaseViewController.Type else {
                return UIViewController()
        }
        
        // 创建视图控制器
        let vc = cls.init()
        vc.title = title
        vc.visitorInfo = visitorInfo
        
        // 设置tabbar图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        
        // 设置tabbar字体颜色
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
    }
    
    /// 设置新特性视图
    func setupNewFeatures() {
        
        if !WBNetworkManager.shared.userLogon {return}
        
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView()
        
        v.frame = view.bounds
        
        view.addSubview(v)
    }
    
    /// 判断是否有新版本的计算型属性
    private var isNewVersion: Bool {
        
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        let path = "version".az_appendDocumentDir()
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
        
        _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        debugPrint(Bundle.main.infoDictionary?["CFBundleShortVersionString"])
        
        return sandboxVersion != currentVersion
    }
}
